package com.power.sifa.runner;

import cn.hutool.core.util.ObjectUtil;
import com.plf.common.cache.CacheManager;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.persistence.Table;
import java.util.Set;

/**
 * 启动时遍历所有的实体类 将tablename - classname信息初始化缓存 key小写
 *
 * @author wangning
 */
@Component
@Order(1)
@Slf4j
@Primary
public class TableMapRunner implements ApplicationRunner {

    @Resource
//    @Qualifier(value = "redisCacheManager")
    private CacheManager cacheManager;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //  行政复议的实体表
        Reflections reflections = new Reflections("com.power.sifa.approve");
        //  复议监督的实体表
        Reflections reflections1 = new Reflections("com.power.sifa.supervise");
        // 行政应诉的实体表
        Reflections reflections2 = new Reflections("com.power.sifa.respond");
        // 社区矫正的实体表
        Reflections reflections3 = new Reflections("com.power.sifa.correction");
        Set<Class<?>> classesList = reflections.getTypesAnnotatedWith(Table.class);
        classesList.addAll(reflections1.getTypesAnnotatedWith(Table.class));
        classesList.addAll(reflections2.getTypesAnnotatedWith(Table.class));
        classesList.addAll(reflections3.getTypesAnnotatedWith(Table.class));
        for (Class clazz : classesList) {
            Table anno = (Table) clazz.getAnnotation(Table.class);
            if (ObjectUtil.isNotNull(anno)) {
                cacheManager.put("TABLE-ENTITY", anno.name().toLowerCase(), clazz.getName());
            }
        }
        log.info("TABLE-ENTITY 表名实体类缓存完成 共 {} 个", classesList.size());
    }

}
